<template>
  <div class="container">
    <header>购物车</header>
    <main>
      <van-empty
        description="购物车当前未添加任何物品"
        v-if="cartList.length == 0"
      />

      <div class="cart-list" v-else>
        <van-row v-for="(item, index) in cartList" :key="item.cartid">
          <van-col span="2">
            <van-checkbox v-model="item.flag" class="che" @click="handleItemCheck"></van-checkbox>
          </van-col>
          <van-col span="22">
            <van-swipe-cell>
              <van-card
                :num="item.num"
                :price="item.originprice"
                :title="item.proname"
                class="goods-card"
                :thumb="item.img1"
              >
                <template #num>
                  <van-stepper
                    v-model="item.num"
                    :min="1"
                    theme="round"
                    button-size="22"
                    disable-input
                    @change="change(item.cartid, $event)"
                  />
                </template>
              </van-card>

              <template #right>
                <van-button
                  square
                  text="删除"
                  type="danger"
                  class="delete-button"
                  @click="remove(item.cartid)"
                />
              </template>
            </van-swipe-cell>
          </van-col>
        </van-row>
      </div>
    </main>
  </div>
     <van-submit-bar :price="totalPrice" button-text="提交订单" @submit="onSubmit">
        <van-checkbox v-model="isAllChecked" @click="checked">全选</van-checkbox>
        <template #tip>
          你的收货地址不支持配送, <span @click="onClickLink">修改地址</span>
        </template>
      </van-submit-bar>
</template>

<script>
import { doCartList, doRemoveCart, doUpdateNum } from "@/apis/cart";


export default {
  data() {
    return {
      cartList: [],
      isAllChecked:true,
      isAllCheckedSync:true
    };
  },
  computed:{
    totalPrice(){
      return this.cartList.filter(item=>item.flag)
      .reduce((sum,item)=>sum+item.originprice*item.num,0)*100
    },
    isAllCheckedSync(){
      return this.carlist.length>0&&this.cartList.every(item=>item.flag)
    }
  },
  created() {
    this.loadCartList();
  },
  methods: {
    checked(){
    this.cartList.forEach(item=>{
      item.flag=this.isAllChecked;
    });
    },
    handleItemCheck(){
      this.isAllChecked=this.isAllCheckedSync;
    },
    loadCartList() {
      const userid = localStorage.getItem("userid");
      doCartList({
        userid: userid,
      })
        .then((res) => {
          console.log(res);
          this.cartList = (res.data.data || []).map((item) => {
            return {
              ...item,
              num: Math.max(1, parseInt(item.num) || 1),
              flag:true,
            };
          });
          this.isAllChecked=this.cartList.length>0&&this.cartList.every(item=>item.flag);
        })
        .catch((error) => {
          console.error("加载购物车失败:", error);
          showToast("加载购物车失败");
        });
    },
    change(cartid, newNum) {
      newNum = parseInt(newNum) || 1;
      if (newNum < 1) {
        showToast("数量不能小于1");
        const targetItem = this.cartList.find((item) => item.cartid === cartid);
        if (targetItem) {
          targetItem.num = 1;
        }
        return;
      }

      // 更新到服务器
      doUpdateNum({ cartid, num: newNum })
        .then((res) => {
          console.log("数量更新成功:", res);
          if (res.data.code !== "200") {
            showToast("数量更新失败");
            this.loadCartList();
          }
        })
        .catch((error) => {
          console.error("数量更新失败:", error);
          showToast("数量更新失败");
          this.loadCartList();
        });
    },

    // 删除商品
    remove(cartid) {
      doRemoveCart({ cartid: cartid })
        .then((res) => {
          console.log(res.data.code);

          if (res.data.code == "200") {
            this.cartList = this.cartList.filter(
              (item) => item.cartid != cartid
            );
            showToast("删除成功");
            console.log(this.cartList);
          } else {
            showToast("删除购物车单条数据失败");
          }
        })
        .catch((error) => {
          console.error("删除失败:", error);
          showToast("删除失败");
        });
    },
  },
};
</script>

<style scoped>
.cart-list{
  max-height: calc(100vh - 180px);
  overflow-y: auto;
  padding-bottom: 10px;
}
/* main{
  height: 300px;
  flex: 0ss;
} */
.van-submit-bar {
  bottom: 42px;
}
.che {
  margin-top: 40px;
  margin-left: 10px;
}
.goods-card {
  margin: 0;
  background-color: white;
}

.delete-button {
  height: 100%;
}

.container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

header {
  background-color: #fff;
  padding: 15px;
  text-align: center;
  font-size: 18px;
  font-weight: bold;
  border-bottom: 1px solid #eee;
}
</style>
